package com.bear.hospital.service.patient.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bear.hospital.entity.DepartmentMap;
import com.bear.hospital.mapper.LoginMapper;
import com.bear.hospital.mapper.PatientMapper;
import com.bear.hospital.pojo.Doctor;
import com.bear.hospital.pojo.LoginMap;
import com.bear.hospital.pojo.Patient;
import com.bear.hospital.service.patient.PatientService;
import com.bear.hospital.utils.Md5Util;
import com.bear.hospital.utils.RandomUtil;
import com.bear.hospital.utils.TodayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service("PatientService")
public class PatientServiceImpl implements PatientService {
    protected static final Logger Log = LoggerFactory.getLogger(PatientServiceImpl.class);

    @Resource
    private PatientMapper patientMapper;
    @Resource
    LoginMapper loginMapper;

    /**
     * 登录数据校验
     */
    @Override
    public Patient login(String pId, String pPassword) {
        Patient patient = this.patientMapper.selectById(pId);
        String password = Md5Util.getMD5(pPassword);
        if (patient == null) {
            return null;
        } else {
            if ((patient.getPPassword()).equals(password)) {
                return patient;
            }
        }
        return null;
    }

    /**
     * 分页模糊查询所有患者信息
     */
    @Override
    public HashMap<String, Object> findAllPatients(int pageNumber, int size, String query) {
        Page<Patient> page = new Page<>(pageNumber, size);
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.like("p_name", query).orderByDesc("p_state");
        IPage<Patient> iPage = this.patientMapper.selectPage(page, wrapper);

        List<String> pid = iPage.getRecords().stream().map(Patient::getPId).collect(Collectors.toList());
        List<LoginMap> loginMapList = loginMapper.queryLogin_mapById("patient",pid);
          Map<String,LoginMap> loginMapMap = loginMapList.stream()
                .collect(Collectors.toMap(
                        LoginMap::getTid, // 键是如何生成的
                        loginmap -> loginmap, // 值是什么
                        (existing, replacement) -> existing));
        HashMap<String, Object> hashMap = new HashMap<>();
        for (Patient patient : iPage.getRecords()){
            LoginMap loginMap = loginMapMap.get(patient.getPId());
            patient.setUserName(loginMap.getUserName());
        }
        hashMap.put("total", iPage.getTotal());       //总条数
        hashMap.put("pages", iPage.getPages());       //总页数
        hashMap.put("pageNumber", iPage.getCurrent());//当前页
        hashMap.put("patients", iPage.getRecords()); //查询到的记录
        return hashMap;
    }

    /**
     * 删除患者信息
     */
    @Override
    public Boolean deletePatient(String pId) {
        Patient patient = new Patient();
        patient.setPId(pId);
        patient.setPState(0);
        this.patientMapper.updateById(patient);
        return true;
    }

    /**
     * 根据患者id查询患者信息
     */
    @Override
    public Patient findPatientById(String pId) {
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("p_id", pId);
        return this.patientMapper.selectOne(wrapper);
    }

    /**
     * 增加患者信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addPatient(Patient patient) {
        //如果账号已存在则返回false
        List<LoginMap> loginMapList = loginMapper.selectByUsername(patient.getUserName());
        if (!loginMapList.isEmpty()){
            return false;
        }
        int yourYear = Integer.parseInt(patient.getPBirthday().substring(0, 4));
        int todayYear = Integer.parseInt(TodayUtil.getTodayYmd().substring(0, 4));
        //密码md5加密
        String password = Md5Util.getMD5(patient.getPPassword());
        patient.setPId(RandomUtil.generateUniqueId());
        patient.setPPassword(password);
        patient.setPAge(todayYear - yourYear);
        patient.setPState(1);
        LoginMap loginMap = new LoginMap();
        loginMap.setCreateTime(TodayUtil.getToday());
        loginMap.setDr("0");
        loginMap.setPhone(patient.getPPhone());
        loginMap.setLoginUrl("/orderOperate");
        loginMap.setIdentity("patient");
        loginMap.setTableName("patient");
        loginMap.setTid(patient.getPId());
        loginMap.setUserName(patient.getUserName());
        loginMapper.insertLoginMap(loginMap);
        this.patientMapper.insert(patient);
        return true;
    }

    /**
     * 统计患者男女人数
     */
    public List<Integer> patientAge() {
        List<Integer> ageList = new ArrayList<>();
        Integer age1 = this.patientMapper.patientAge(0, 9);
        Integer age2 = this.patientMapper.patientAge(10, 19);
        Integer age3 = this.patientMapper.patientAge(20, 29);
        Integer age4 = this.patientMapper.patientAge(30, 39);
        Integer age5 = this.patientMapper.patientAge(40, 49);
        Integer age6 = this.patientMapper.patientAge(50, 59);
        Integer age7 = this.patientMapper.patientAge(60, 69);
        Integer age8 = this.patientMapper.patientAge(70, 79);
        Integer age9 = this.patientMapper.patientAge(80, 89);
        Integer age10 = this.patientMapper.patientAge(90, 99);
        ageList.add(age1);
        ageList.add(age2);
        ageList.add(age3);
        ageList.add(age4);
        ageList.add(age5);
        ageList.add(age6);
        ageList.add(age7);
        ageList.add(age8);
        ageList.add(age9);
        ageList.add(age10);
        return ageList;

    }

    @Override
    public List<HashMap<String, Object>> findDoctorBySectionPage() {
        List<DepartmentMap> departmentMapList = patientMapper.queryDepartmentMap();
        Map<String, List<DepartmentMap>> collect = departmentMapList.stream().collect(Collectors.groupingBy(DepartmentMap::getOneLevelDepartment));
        List<HashMap<String, Object>> respone = new ArrayList<>();

        collect.forEach((k, v) -> {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("text", k);
            System.out.println("一级科室: " + k);
            List<Map<String, String>> towDeptList = new ArrayList<>();
            v.forEach(department -> {
                        HashMap<String, String> towDeptMap = new HashMap<>();
                        towDeptMap.put("text", department.getTwoLevelDepartment());
                        towDeptMap.put("id", department.getId());
                        towDeptList.add(towDeptMap);
                    });
            hashMap.put("children", towDeptList);
            respone.add(hashMap);
        });
        return respone;
    }


}


